const cheerio = require('cheerio');
const download = require('download'); // 下载图片库
const request = require('request');
const Iconv = require('iconv-lite');
const path = require('path');
// const fs = require('fs');

const headers = {
  'User-Agent':
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36'
};

// 异步执行函数，用于下载图片
async function downloadImg(list) {
  Promise.all(
    list.map(async (item, index) => {
      // 方法一
      const directory = path.resolve(__dirname, '../../image'); // 存放目录
      await download(item.bigImg, directory, {
        filename: Math.random().toString(16).slice(2, 7) + index + '.jpg',
        headers
      })
        .then(() => {
          console.log(`Download ${item.bigImg} Completed`);
        })
        .catch(err => {
          console.log(err, 2324);
        });
      // 方法二 (原生写入)
      // const filename = Math.random().toString(16).slice(2, 7) + index;
      // request({ url: item.bigImg }).pipe(
      //   fs
      //     .createWriteStream(path.resolve(__dirname, `../../image/${filename}.jpg`))
      //     .on('close', err => {
      //       if (err) {
      //         console.log(err, `${item.bigImg}下载失败啦`);
      //       }
      //     })
      // );
    })
  )
    .then(() => {
      console.log('Download complete');
    })
    .catch(err => {
      console.log(err, '所有图片地址下载错误');
    });
}

/**
 * GET /api/down-img
 * @tags 彼岸桌面图片
 * @summary 彼岸桌面图片
 * @description 彼岸桌面图片
 * @param {string}  page.query.required  - page 页码
 */
module.exports = (req, res) => {
  const { page = 1 } = req.query;
  const search = page == 1 ? '' : '_' + page;
  let url = `http://www.netbian.com/index${search}.htm`;
  let headers = {
    'Proxy-Connection': 'keep-alive',
    Host: 'www.netbian.com',
    Referer: 'http://www.netbian.com/meinv/index.htm',
    Accept:
      'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Upgrade-Insecure-Requests': 1,
    Connection: 'keep-alive',
    'User-Agent':
      'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36'
  };
  request(
    {
      url: url,
      encoding: null,
      headers: headers
    },
    function (error, response, body) {
      if (error) {
        return res.api_error('请求页面不存在', 5001);
      }
      if (response && response.statusCode === 200) {
        body = Iconv.decode(body, 'gb2312');
        const $ = cheerio.load(body, { decodeEntities: false });
        let tmp = [];
        $('.list li').each(function (i, ele) {
          let img = $(ele).find('img').attr('src');
          let bigImg = img.replace('small', '').split('16')[0] + '.jpg';
          let title = $(ele).text();
          let imgList = {
            img,
            bigImg,
            title
          };
          tmp.push(imgList);
        });
        res.api_success({ total: tmp.length, imglist: tmp });
        // 下载图片
        downloadImg(tmp);
      } else {
        res.api_error('页面错误,解析数据异常', 5001);
      }
    }
  );
};
